/* eslint-disable no-path-concat */
const fs = require('fs');
const archiver = require('archiver');
const axios = require('axios');

const SocksProxyAgent = require('socks-proxy-agent');
const httpsAgent = new SocksProxyAgent('socks5://127.0.0.1:1080');

axios.interceptors.request.use(function(config) {
  config.proxy = false;
  config.httpAgent = httpsAgent;
  config.httpsAgent = httpsAgent;
  return config;
});

const webStore = require('./webstore')({
  extensionId: 'pakjjhlejpocgnbomcimfpalfcbhmpah',
  clientId:
    '952828821253-ckuhbu4hnvb54apsj77jcour2b811ej8.apps.googleusercontent.com',
  clientSecret: 'FTF8N6QMjFLK_f4861_fxQn9',
  refreshToken: '1/OwaseGOG_fRUiBvyAtvajW939PtlllOLRxedRrrkTj8'
});

let output = fs.createWriteStream(__dirname + '/dist/extension.zip');
let archive = archiver('zip', {
  zlib: { level: 9 } // Sets the compression level.
});

archive.pipe(output);
archive.directory('src/', false);
archive.finalize();

output.on('close', function() {
  console.log(archive.pointer() + ' total bytes');

  const nodeParams = process.argv.splice(2);
  if (nodeParams && nodeParams[0] === 'dev') {
    console.log('build dev ok');
    return;
  }
  webStore
    .fetchToken()
    .then(token => {
      const outputFile = fs.createReadStream(__dirname + '/dist/extension.zip');
      console.log(
        'archiver has been finalized and the output file descriptor has closed.'
      );
      // eslint-disable-next-line consistent-return
      return webStore.uploadExisting(outputFile, token).then(res => {
        if (res.uploadState === 'SUCCESS') {
          console.log('upload ok');

          // eslint-disable-next-line no-shadow
          return webStore.publish('default', token).then(res => {
            if (res.item_id && res.status && res.status[0] === 'OK') {
              console.log('publish ok');
              console.log(JSON.stringify(res));
              let crxUrl = `https://clients2.google.com/service/update2/crx?response=redirect&prodversion=77.0.3865.90&acceptformat=crx2,crx3&x=id%3D${res.item_id}%26installsource%3Dondemand%26uc`;
              return axios
                .request({
                  responseType: 'arraybuffer',
                  url: crxUrl,
                  method: 'get'
                })
                .then(result => {
                  fs.writeFileSync(
                    __dirname + '/dist/caishui.crx',
                    result.data
                  );
                  console.log('download ok');
                })
                .catch(e => {
                  console.error('download failed');
                  return Promise.reject(e);
                });
            }
            return Promise.reject(res);
          });
        }
        return Promise.reject(res);
      });
    })
    .catch(e => {
      console.log(JSON.stringify(e));
      process.exit(1);
    });
});
